from flask_login import UserMixin

from market import db, login_manager, bcrypt


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    password_hash = db.Column(db.String(60), nullable=False)
    items = db.relationship('Goods', backref='owned', lazy=True)

    def __init__(self, username, password_hash):
        self.username = username
        self.password_hash = password_hash

    def check_password_correction(self, attempted_password):
        """
        验证输入的密码与存储的哈希密码是否匹配。

        :param attempted_password: 尝试登录时输入的明文密码
        :return: 如果密码匹配返回 True，否则返回 False
        """
        return bcrypt.check_password_hash(self.password_hash, attempted_password)


class Goods(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), unique=True, nullable=False)
    price = db.Column(db.Integer, nullable=False)
    owner = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f'<Goods {self.name}>'
